class Subject:
    def __init__(self):
        self._observers = []
        self._state = None

    def attach(self, observer):
        """注册观察者"""
        if observer not in self._observers:
            self._observers.append(observer)

    def detach(self, observer):
        """注销观察者"""
        try:
            self._observers.remove(observer)
        except ValueError:
            pass

    def notify(self):
        """通知所有观察者"""
        for observer in self._observers:
            observer.update(self)

    def set_state(self, state):
        """设置主题状态，并通知所有观察者"""
        self._state = state
        self.notify()

    def get_state(self):
        """获取主题状态"""
        return self._state


class Observer:
    def update(self, subject):
        """当主题状态变化时调用"""
        raise NotImplementedError("update method must be implemented")


class ConcreteObserver(Observer):
    def update(self, subject):
        print(f"Observer notified: {subject.get_state()}")

    # 使用示例


if __name__ == "__main__":
    subject = Subject()
    observer1 = ConcreteObserver()
    observer2 = ConcreteObserver()

    subject.attach(observer1)
    subject.attach(observer2)

    subject.set_state("New state!")

    # 输出：
    # Observer notified: New state!
    # Observer notified: New state!

    subject.detach(observer1)
    subject.set_state("Another new state!")

    # 输出：
    # Observer notified: Another new state!

"""
Observer notified: New state!
Observer notified: New state!
Observer notified: Another new state!
"""
